<template>
  <div class="common-wrap">
    <QueryForm
      ref="conditionForm"
      module="boxType"
      :searchBtnLoading="loading"
      v-model:searchForm="searchForm"
      v-model:search-column="searchColumn"
      @handle-search="onSearch"
    />
    <div class="common-box">
      <el-row style="height: 40px" class="con-button-rows">
        <ButtonGroup
          :disabledDelete="multipleSelection.length === 0"
          :hasPermiAdd="['common:boxType:add']"
          :hasPermiDelete="['common:boxType:delete']"
          :buttonType="['add', 'delete']"
          @add="onAdd"
          @delete="onDelete"
        ></ButtonGroup>
      </el-row>
      <MyTable
        tableId="boxType"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :keepSource="true"
        :changeEditNeedTrigger="true"
        :pageVo="pageVo"
        :edit-rules="editRules"
        keepSourceKey="containerCode"
        :edit-config="{
          trigger: 'click',
          mode: 'row',
          showStatus: true,
          enabled: hasPermi(['common:boxType:edit']),
        }"
        ref="boxTypeTable"
        moduleName="boxType"
        @handleSelectionChange="handleSelectionChange"
        @handle-page-change="handlePageChange"
        @handleEditClosed="handleEditClosed"
      ></MyTable>
    </div>
  </div>
</template>

<script setup lang='tsx'>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import * as api from "@/api/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { hasPermi } from "@/utils/mUtils.js";
import {
  tabelColumnFilters,
  getSubZhEn,
  queryFormColumnFilters,
} from "@/utils/mUtils.js";
let { t } = useI18n();
defineOptions({
  name: "BoxType",
});
const pageVo = reactive({
  pageSize: 50,
  total: 10,
  currentPage: 1,
  status: true,
});
const loading = ref(true);
const dataSource = ref([]);
const columns = ref([
  {
    type: "checkbox",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    title: "序号",
    type: "seq",
    width: 60,
    fixed: "left",
  },
  {
    field: "containerCode",
    title: "箱型代码",
    editRender: {},
    slots: { edit: "input_edit" },
    width: 200,
  },
  {
    field: "specificationsCode",
    title: "规格",
    editRender: {},
    params: {
      options: [],
      change: (val, rowIndex, row, options) => {
        row.specificationsName = val.option.label;
      },
      key: "subName",
      value: "subCode",
      label: "subName",
    },
    slots: { edit: "select_edit" },
    formatter: ({ cellValue, row }) => {
      return row.specificationsName;
    },
    width: 200,
  },
  {
    field: "teuConversionFactor",
    title: "标箱量系数",
    editRender: {},
    slots: { edit: "input_edit" },
    params: {
      type: "number",
      digits: 2,
    },
    width: 200,
  },
  {
    field: "maxGrossWeight",
    title: "最大载重(KG)",
    editRender: {},
    slots: { edit: "input_edit" },
    params: {
      type: "number",
      digits: 2,
    },
    width: 200,
  },
  {
    field: "maxCubicCapacity",
    title: "最大体积(m3)",
    editRender: {},
    slots: { edit: "input_edit" },
    params: {
      type: "number",
      digits: 2,
    },
    width: 200,
  },
  {
    field: "amsTypeCode",
    title: "AMS Type Code",
    editRender: {},
    slots: { edit: "input_edit" },
    width: 200,
  },
  {
    field: "remark",
    title: "备注",
    editRender: {},
    slots: { edit: "input_edit" },
    width: 250,
  },
  {
    field: "sort",
    title: "排序",
    editRender: {},
    slots: { edit: "input_edit" },
    params: {
      type: "number",
    },
    width: 200,
  },
]);
const searchForm = reactive({});
const searchColumn = ref([
  {
    type: "label_select",
    label: "规格",
    options: [],
    prop: "specificationsCode",
  },
  {
    type: "label_input",
    label: "箱型代码",
    prop: "containerCode",
  },
]);
const multipleSelection = ref([]);
const boxTypeTable = ref();
const editRules = ref({
  containerCode: [
    {
      required: true,
      message: t("请输入箱型代码"),
    },
  ],
  specificationsCode: [
    {
      required: true,
      message: t("请选择币种"),
    },
  ],
  teuConversionFactor: [
    {
      required: true,
      message: t("请输入TEU系数"),
    },
  ],
});
onMounted(() => {
  onSearch();
  onGetSub();
});
const onGetSub = () => {
  getSubZhEn({
    code: "004",
  }).then((res) => {
    tabelColumnFilters(columns.value, "specificationsCode").params.options =
      res["004"];
    queryFormColumnFilters(searchColumn.value, "specificationsCode").options =
      res["004"];
  });
};
const list = () => {
  loading.value = true;
  api.default.common.boxType
    .list({
      ...searchForm,
      pageNum: pageVo.currentPage,
      pageSize: pageVo.pageSize,
    })
    .then((res) => {
      dataSource.value = res.rows;
      loading.value = false;
      pageVo.total = res.total;
    })
    .catch(() => {
      loading.value = false;
    });
};

const onAdd = async (row) => {
  const $grid = boxTypeTable.value.$refs.xGrid;
  const record = {
    containerCode: "",
  };
  dataSource.value.unshift(record);
  const nerow = dataSource.value[0];
  await $grid.setEditCell(nerow, "containerCode");
};
const handleEditClosed = async (row, rowIndex, resolve, reject) => {
  const error = await boxTypeTable.value.rowFullValidEvent(row);
  if (error) {
    ElMessage.error(`${t("第")}${rowIndex + 1}${t("行！请填写必填字段")}`);
    return;
  }
  try {
    if (!row.id) {
      await api.default.common.boxType.add(row);
      ElMessage.success(t("新增成功"));
      onSearch();
    } else {
      await api.default.common.boxType.edit(row);
      ElMessage.success(t("修改成功"));
    }
    resolve();
  } catch (e) {
    reject();
  }
};
const onDelete = () => {
  const ids = multipleSelection.value
    .filter((item) => item.id)
    .map((item) => item.id);
  if (!ids.length) {
    dataSource.value = dataSource.value.filter((item) => {
      return !multipleSelection.value.find((row) => row.rowId === item.rowId);
    });
    return;
  }
  ElMessageBox.confirm(t("是否确定删除当前选择数据？"), t("提示"), {
    confirmButtonText: t("确定"),
    cancelButtonText: t("取消"),
    type: "warning",
  })
    .then(() => {
      api.default.common.boxType.remove(ids).then(() => {
        ElMessage.success(t("删除成功"));
        onSearch();
      });
    })
    .catch(() => {});
};
const handleSelectionChange = (list) => {
  multipleSelection.value = list;
};
const handlePageChange = (val) => {
  const { currentPage, pageSize } = val;
  pageVo.currentPage = currentPage;
  pageVo.pageSize = pageSize;
  list();
};
const onSearch = () => {
  pageVo.currentPage = 1;
  list();
};
</script>

<style lang="scss" scoped>
.pcMenu {
  height: 100%;
  width: 100%;
  background: #fff;
}
</style>